package org.water.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.water.datasources.DataSourceName;
import org.water.datasources.DynamicDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置多数据源
 * @author qzy
 *
 */
@Configuration
public class DynamicDataSourceConfig {

	protected Logger log=LogManager.getLogger(getClass());
	
	
    @Bean @Qualifier("defaultDataSource")
    @ConfigurationProperties("spring.datasource.druid.default")
    public DataSource defaultDataSource(){
		log.info("创建默认数据源");
        return DruidDataSourceBuilder.create().build();
    }

//    @Bean @Qualifier("exampleDataSource")
//    @ConfigurationProperties("spring.datasource.druid.example")
//    public DataSource exampleDataSource(){
//        return DruidDataSourceBuilder.create().build();
//    }

//    @Bean
//    @Primary
//    public DynamicDataSource dataSource(DataSource defaultDataSource, DataSource exampleDataSource) {
//        Map<Object, Object> targetDataSources = new HashMap<>();
//        targetDataSources.put(DataSourceName.DEFAULT, defaultDataSource);
//        targetDataSources.put(DataSourceName.EXAMPLE, exampleDataSource);
//        return new DynamicDataSource(defaultDataSource, targetDataSources);
//    }
    
    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource defaultDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceName.DEFAULT, defaultDataSource);
//        targetDataSources.put(DataSourceName.EXAMPLE, exampleDataSource);
        return new DynamicDataSource(defaultDataSource, targetDataSources);
    }
}
